import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:liquid_progress_indicator/liquid_progress_indicator.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:provide/provide.dart';
import 'package:qgchat/http/apis/user.dart';
import 'package:qgchat/http/models/UserGetAnchorWechatModel.dart';
import 'package:qgchat/http/models/giftModel.dart';
import 'package:qgchat/http/models/wsAllGiftModel.dart';
import 'component/dialogue.dart';
import 'component/input.dart';
import 'package:qgchat/bloc/live/live.dart';
import 'package:qgchat/common/class/toUserInfo/toUserInfo.dart';
import 'package:qgchat/page/live/videoPage/anchorGiftBox.dart';
import 'package:qgchat/states/states_model/socket.dart';
import 'package:qgchat/states/states_model/user.dart';
import 'package:qgchat/widgets/tipsDialog.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/bloc/blocProvider.dart';
import '../giftBox.dart';
import 'dart:async';
import 'dart:ui';

class LiveView extends StatefulWidget {
  LiveView(
    this.isAnchor,
    this.isReceive,
    this.inv,
    this.userId,
    this.anchorId,
    this.targetName,
    this.targetHead,
    this.targetToken, {
    Key key,
  }) : super(key: key);

  final bool isAnchor;
  final bool isReceive;
  final int inv;
  final int userId;
  final int anchorId;
  final String targetName;
  final String targetHead;
  final String targetToken;

  @override
  _LiveViewState createState() => _LiveViewState();
}

class _LiveViewState extends State<LiveView> with WidgetsBindingObserver {
  LiveBloc bloc;

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
        break;
      case AppLifecycleState.resumed: // 应用程序可见，前台
        bloc.openLocalVideo();
        print('视频前台');
        break;
      case AppLifecycleState.paused: // 应用程序不可见，后台
        bloc.closeLocalVideo();
        print('视频后台');
        break;
      case AppLifecycleState.detached: // 申请将暂时暂停
        break;
    }
  }

  @override
  void initState() {
    super.initState();
    if (mounted) {
      // 隐藏状态栏
      SystemChrome.setEnabledSystemUIOverlays([]);

      Global.audio.stopAllAudio();
      WidgetsBinding.instance.addObserver(this); // 监听app状态
      // 初始化bloc
      bloc = BlocProvider.of<LiveBloc>(context);
      bloc.closeVideoStream.listen((isClose) {
        if (isClose) {
          goPageVideoEnd();
        }
      });

      socketListen();

      agoraListen();
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this); // 销毁监听app状态
    // 显示状态栏
    SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
    super.dispose();
  }

  // socket监听
  socketListen() {
    final not = Global.socketNot;
    if (not.value != null) {
      final decodeSteam = not.value.map((str) => jsonDecode(str));

      // 鉴黄师警告
      decodeSteam.where((cls) => cls['datatype'] == 'warning').listen(
        (res) {
          showDialog(
            context: context,
            builder: (BuildContext context) {
              return _WarnDialog(
                title: "警告⚠️",
                msg: [
                  "本次视频检测到违规内容",
                  "若多次违规",
                  "本次视频将会被强制结束",
                ],
                timeOut: 5,
              );
            },
          );
        },
      );

      // 鉴黄师中断视频
      decodeSteam.where((cls) => cls['datatype'] == 'violation').listen(
        (res) {
          showDialog(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context) {
              return _WarnDialog(
                title: "中断通知⚠️",
                msg: [
                  "因检测到违规内容",
                  "本次视频将会强制结束",
                ],
                confirmFn: goPageVideoEnd,
                closeFn: goPageVideoEnd,
                timeOut: 5,
              );
            },
          );
        },
      );
    }
  }

  // 声网监听
  agoraListen() {
    // 监听对方离开频道
    // AgoraRtcEngine.onUserOffline = (int uid, int reason) {
    //   String reasonString = "未知原因";
    //   switch (reason) {
    //     case 0:
    //       reasonString = "用户主动离开";
    //       break;
    //     case 1:
    //       reasonString = "长时间收不到对方数据包，超时掉线";
    //       break;
    //     case 2:
    //       reasonString = "用户身份从主播切换为观众（直播模式下）";
    //       break;
    //   }
    //   print("### 远端用户 $uid 离开频道, 离线原因：$reasonString ###");

    //   if (widget.isAnchor && uid == widget.userId) {
    //     toast('对方已离开频道');
    //     goPageVideoEnd();
    //   }
    //   ;
    //   if (!widget.isAnchor && uid == widget.anchorId) {
    //     toast('对方已离开频道');
    //     goPageVideoEnd();
    //   }
    // };
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _quit,
      child: Scaffold(
        resizeToAvoidBottomPadding: false,
        backgroundColor: Colors.black,
        body: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            // 大视频窗口
            _bigVideoViewsRender(),
            // 小视频窗口
            _smallVideoViewsRender(),
            // 工具栏组件
            _toolbarHandle(),
            // 对话框组件
            _dialogueHandle(),
            // 通话计时
            _callDuration(),
            // 输入框组件
            // _inputHandle(),
            // 对方信息组件
            _otherInfoHandle(),
            // 亲密度进度
            _Intimacy(token: widget.targetToken),
          ],
        ),
      ),
    );
  }

  // 大屏视频窗口
  _bigVideoViewsRender() {
    UserState user = state(context, 'user');

    /// 主播 大屏自己
    if (widget.isAnchor) {
      return _bigView(
        stream: bloc.showMyViewStream,
        defaultData: bloc.myViewDefault,
        head: user.info.memberHead,
        name: user.info.memberNickname,
      );
    }

    /// 用户 大屏对方
    else {
      return _bigView(
        stream: bloc.anchorJoinedStream,
        defaultData: bloc.anchorJoinedDefault,
        head: widget.targetHead,
        name: widget.targetName,
      );
    }
  }

  // 大窗
  _bigView({
    stream,
    defaultData,
    head,
    name,
  }) {
    return StreamBuilder(
      stream: stream,
      initialData: defaultData,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.data) {
          return FutureBuilder(
            future: Future.delayed(Duration(milliseconds: 1500))
                .then((value) => true),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return Container(
                  width: w100(context),
                  height: h100(context),
                  child: bloc.agora.identityVideoViewsRender(view: "big"),
                );
              } else {
                return Container(color: Colors.black);
              }
            },
          );
        } else {
          return Container(
            width: w100(context),
            height: h100(context),
            color: Colors.white,
            child: Stack(
              children: <Widget>[
                Image.network(
                  head,
                  fit: BoxFit.cover,
                ),
                BackdropFilter(
                  filter: ImageFilter.blur(sigmaX: 30, sigmaY: 30),
                  child: Container(
                    color: Colors.white.withAlpha(0),
                  ),
                ),
                Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        width: px(300),
                        height: px(300),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(
                            Radius.circular(px(12)),
                          ),
                          image: DecorationImage(
                            image: NetworkImage("$head"),
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: px(30)),
                        padding: EdgeInsets.symmetric(
                          horizontal: px(30),
                          vertical: px(5),
                        ),
                        decoration: BoxDecoration(
                          color: Colors.black.withOpacity(.24),
                          borderRadius: BorderRadius.all(
                            Radius.circular(px(30)),
                          ),
                        ),
                        child: Text(
                          "$name",
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: px(34),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          );
        }
      },
    );
  }

  // 小屏视频窗口
  _smallVideoViewsRender() {
    UserState user = state(context, 'user');

    /// 主播 小屏对方
    if (widget.isAnchor) {
      return _smallView(
        stream: bloc.anchorJoinedStream,
        defaultData: bloc.anchorJoinedDefault,
        head: widget.targetHead,
      );
    }

    /// 用户 小屏自己
    else {
      return _smallView(
        stream: bloc.showMyViewStream,
        defaultData: bloc.myViewDefault,
        head: user.info.memberHead,
      );
    }
  }

  /// 小窗
  _smallView({
    stream,
    defaultData,
    head,
  }) {
    return StreamBuilder(
      stream: stream,
      initialData: defaultData,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.data) {
          return Positioned(
            top: px(88),
            right: px(30),
            child: stateBuilder(context, 'user', (UserState user) {
              return Container(
                width: px(246),
                height: px(327),
                child: bloc.agora.identityVideoViewsRender(view: "small"),
              );
            }),
          );
        } else {
          return Positioned(
            top: px(88),
            right: px(30),
            child: Container(
              width: px(246),
              height: px(327),
              child: Image.network(
                "$head",
                fit: BoxFit.cover,
              ),
            ),
          );
        }
      },
    );
  }

  // 对方信息按钮
  _otherInfoAction(context) {
    bloc.toggleAnchorData(context, widget.targetToken);
  }

  // 礼物按钮
  _giftAction() {
    UserState user = state(context, 'user');
    if (user.info.memberType == 1) {
      showModalBottomSheet(
        context: context,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(px(24)),
            topRight: Radius.circular(px(24)),
          ),
        ),
        builder: (BuildContext context) {
          return AnchorGiftBox(token: widget.targetToken);
        },
      );
    } else {
      showModalBottomSheet(
        context: context,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(px(24)),
            topRight: Radius.circular(px(24)),
          ),
        ),
        builder: (BuildContext context) {
          return GiftBox(token: widget.targetToken, canShowSvga: true);
        },
      );
    }
  }

  // 美颜按钮
  _beautyAction() {}

  // 开关摄像���按钮
  _switchCameraAction() {
    bloc.enableLocalVideo();
    if (bloc.agora.enabled) {
      showToast("镜头已开启");
    } else {
      showToast("镜头已关闭");
    }
  }

  // 切换摄像头按钮
  _changeCameraAction() {
    bloc.agora.switchCamera();
    showToast("已切换镜头");
  }

  // 退出视频通话按钮
  _closeVideoAction() async {
    bool isQuit = await _chooseQuit();
    if (isQuit) {
      goPageVideoEnd();
    }
  }

  // 退出视频通话
  Future<bool> _quit() async {
    bool isQuit = await _chooseQuit();
    if (isQuit) {
      goPageVideoEnd();
    }
  }

  // 跳转通话完毕页面
  goPageVideoEnd() {
    SocketState socketState = state(context, 'socket');
    socketState.toggleCallState(false);

    if (bloc.invId != null && bloc.isStart) {
      Timer(Duration(milliseconds: 3000), () {
        Navigator.pushReplacementNamed(context, "/liveEnd", arguments: {
          "inv": bloc.invId,
          "anchorId": widget.anchorId,
          "targetName": widget.targetName,
          "targetHead": widget.targetHead,
          "targetToken": widget.targetToken,
        });
      });
    } else {
      if (!ModalRoute.of(context).isCurrent) {
        Navigator.of(context).popUntil(ModalRoute.withName('/live'));
      }
      Navigator.pop(context);
    }
  }

  // 用户选择是否退出视频弹窗
  Future<bool> _chooseQuit() async {
    bool userChoiceClose = false;
    await TipsDialog.tryCloseVideo(
      context,
      () => userChoiceClose = true,
    );
    if (userChoiceClose) {
      // Global.ws.refuseVideo(widget.inv);
      Global.ws.stoptalk(widget.targetToken, msg: "对方挂断了通话");
    }
    return userChoiceClose;
  }

  // 工具栏组件
  _toolbarHandle() {
    return Positioned(
      bottom: px(200),
      right: px(30),
      child: Container(
        width: px(88),
        child: Column(
          children: <Widget>[
            // 礼物
            Container(
              width: px(70),
              height: px(70),
              margin: EdgeInsets.only(top: px(40)),
              decoration: BoxDecoration(
                color: col("ffb240"),
                borderRadius: BorderRadius.circular(px(35)),
              ),
              child: FlatButton(
                onPressed: _giftAction,
                padding: EdgeInsets.all(0),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(
                    sp(35),
                  ),
                ),
                child: Image.asset(
                  "assets/images/icon/gift_white.png",
                  width: px(44),
                  height: px(48),
                  fit: BoxFit.contain,
                ),
              ),
            ),
            // 开关摄像头
            // Container(
            //   width: px(70),
            //   height: px(70),
            //   margin: EdgeInsets.only(top: px(40)),
            //   decoration: BoxDecoration(
            //     color: col("04040f").withOpacity(.4),
            //     borderRadius: BorderRadius.circular(px(35)),
            //   ),
            //   child: FlatButton(
            //     onPressed: _switchCameraAction,
            //     padding: EdgeInsets.all(0),
            //     shape: RoundedRectangleBorder(
            //       borderRadius: BorderRadius.circular(
            //         sp(35),
            //       ),
            //     ),
            //     child: Image.asset(
            //       "assets/images/icon/close_camera.png",
            //       width: px(40),
            //       height: px(44),
            //       fit: BoxFit.cover,
            //     ),
            //   ),
            // ),
            // 切换摄像头
            Container(
              width: px(70),
              height: px(70),
              margin: EdgeInsets.only(top: px(40)),
              decoration: BoxDecoration(
                color: col("04040f").withOpacity(.4),
                borderRadius: BorderRadius.circular(px(35)),
              ),
              child: FlatButton(
                onPressed: _changeCameraAction,
                padding: EdgeInsets.all(0),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(
                    sp(35),
                  ),
                ),
                child: Image.asset(
                  "assets/images/icon/change_camera.png",
                  width: px(44),
                  height: px(36),
                  fit: BoxFit.cover,
                ),
              ),
            ),
            // 停止通话
            Container(
              width: px(70),
              height: px(70),
              margin: EdgeInsets.only(top: px(40)),
              decoration: BoxDecoration(
                color: col("04040f").withOpacity(.4),
                borderRadius: BorderRadius.circular(px(35)),
              ),
              child: FlatButton(
                onPressed: _closeVideoAction,
                padding: EdgeInsets.all(0),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(
                    sp(35),
                  ),
                ),
                child: Image.asset(
                  "assets/images/icon/close.png",
                  width: px(38),
                  height: px(38),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 通话计时
  _callDuration() {
    return StreamBuilder(
      stream: bloc.viewTimeStream,
      initialData: "00:00:00",
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        return Positioned(
          left: px(30),
          top: px(178),
          child: Container(
            width: px(150),
            height: px(50),
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(.24),
              borderRadius: BorderRadius.circular(px(25)),
            ),
            child: Center(
              child: Text(
                "${snapshot.data}",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: px(26),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  // 对方信息组件
  _otherInfoHandle() {
    return Positioned(
      top: px(88),
      left: px(30),
      child: Container(
        height: px(60),
        decoration: BoxDecoration(
          color: Colors.black.withOpacity(.24),
          borderRadius: BorderRadius.circular(px(30)),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(right: px(30)),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  GestureDetector(
                    onTapUp: (i) {
                      ToUserInfo.show(context, widget.targetToken);
                    },
                    child: Container(
                      width: px(60),
                      height: px(60),
                      decoration: BoxDecoration(
                        image: DecorationImage(
                          image: NetworkImage(
                            "${widget.targetHead}",
                          ),
                          fit: BoxFit.cover,
                        ),
                        border: Border.all(
                          color: Colors.white,
                          width: px(2),
                        ),
                        borderRadius: BorderRadius.circular(px(30)),
                      ),
                    ),
                  ),
                  Container(
                    height: px(60),
                    padding: EdgeInsets.only(
                      top: px(5),
                      bottom: px(3),
                      left: px(20),
                    ),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          "${widget.targetName}",
                          style: TextStyle(
                            height: .99,
                            color: Colors.white,
                            fontSize: px(26),
                          ),
                        ),
                        Text(
                          "id: ${!widget.isAnchor ? widget.anchorId : widget.userId}",
                          style: TextStyle(
                            height: .99,
                            color: Colors.white,
                            fontSize: px(20),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Container(
              width: px(150),
              padding: EdgeInsets.all(0),
              decoration: BoxDecoration(
                color: Colors.red,
                borderRadius: BorderRadius.circular(
                  px(40),
                ),
              ),
              child: FlatButton(
                padding: EdgeInsets.all(0),
                onPressed: () {
                  showCupertinoModalPopup<int>(
                    context: context,
                    builder: (context) {
                      return CupertinoActionSheet(
                        message: Text(
                          '请选择举报类型',
                          style: TextStyle(
                            color: col("606266"),
                            fontSize: px(26),
                          ),
                        ),
                        cancelButton: CupertinoActionSheetAction(
                          onPressed: () => Navigator.pop(context),
                          child: Text(
                            "取消",
                            style: TextStyle(
                              color: col("157efb"),
                              fontSize: px(40),
                            ),
                          ),
                        ),
                        actions: <Widget>[
                          CupertinoActionSheetAction(
                            onPressed: () {
                              bloc.reportAnthor(1);
                              Navigator.pop(context, 1);
                            },
                            child: Text(
                              "色情，赌博，毒品",
                              style: TextStyle(
                                color: col("303133"),
                                fontSize: px(40),
                              ),
                            ),
                          ),
                          CupertinoActionSheetAction(
                            onPressed: () {
                              bloc.reportAnthor(2);
                              Navigator.pop(context, 2);
                            },
                            child: Text(
                              "谣言,社会负面,诈骗, 邪教",
                              style: TextStyle(
                                color: col("303133"),
                                fontSize: px(40),
                              ),
                            ),
                          ),
                          CupertinoActionSheetAction(
                            onPressed: () {
                              bloc.reportAnthor(3);
                              Navigator.pop(context, 3);
                            },
                            child: Text(
                              "邪教,非法聚会,传销",
                              style: TextStyle(
                                color: col("303133"),
                                fontSize: px(40),
                              ),
                            ),
                          ),
                          CupertinoActionSheetAction(
                            onPressed: () {
                              bloc.reportAnthor(4);
                              Navigator.pop(context, 3);
                            },
                            child: Text(
                              "医药,整形,虚假广告",
                              style: TextStyle(
                                color: col("303133"),
                                fontSize: px(40),
                              ),
                            ),
                          ),
                          CupertinoActionSheetAction(
                            onPressed: () {
                              bloc.reportAnthor(5);
                              Navigator.pop(context, 3);
                            },
                            child: Text(
                              "有奖集攒和关注转发",
                              style: TextStyle(
                                color: col("303133"),
                                fontSize: px(40),
                              ),
                            ),
                          ),
                          CupertinoActionSheetAction(
                            onPressed: () {
                              bloc.reportAnthor(6);
                              Navigator.pop(context, 3);
                            },
                            child: Text(
                              "违法国家政策和法律",
                              style: TextStyle(
                                color: col("303133"),
                                fontSize: px(40),
                              ),
                            ),
                          ),
                        ],
                      );
                    },
                  );
                },
                child: Text(
                  '举报',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  // 输入框组件
  _inputHandle() {
    return Positioned(
      bottom: px(70),
      child: LiveInput(widget.targetToken),
    );
  }

  // 对话框组件
  _dialogueHandle() {
    return Positioned(
      left: px(30),
      bottom: px(180),
      child: LiveDialogue(),
    );
  }
}

class _WarnDialog extends StatefulWidget {
  final String title;
  final List<String> msg;
  final String closeText;
  final String confirmText;
  final Function closeFn;
  final Function confirmFn;
  final bool closeWillClose;
  final bool confirmWillClose;
  final int timeOut;

  _WarnDialog({
    this.title = '提示',
    this.msg = const [],
    this.closeText = '取消',
    this.confirmText = '确认',
    this.closeFn,
    this.confirmFn,
    this.closeWillClose = true,
    this.confirmWillClose = true,
    this.timeOut = 0,
    Key key,
  }) : super(key: key);

  @override
  __WarnDialogState createState() => __WarnDialogState();
}

class __WarnDialogState extends State<_WarnDialog> {
  Timer timer;

  int count = 0;

  @override
  void initState() {
    super.initState();
    if (widget.timeOut > 0) {
      timer = Timer.periodic(
        Duration(seconds: widget.timeOut),
        (timer) {
          if (widget.timeOut == count) {
            Navigator.pop(context);
            if (widget.confirmFn != null) widget.confirmFn();
          } else {
            count++;
            setState(() {});
          }
        },
      );
    }
  }

  @override
  void dispose() {
    super.dispose();
    timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return CupertinoAlertDialog(
      title: Text(
        "${widget.title}",
        style: TextStyle(
          color: col("1e1e1e"),
          fontSize: px(34),
          fontWeight: FontWeight.bold,
        ),
      ),
      content: SingleChildScrollView(
        child: ListBody(
          children: List.generate(
            widget.msg.length,
            (i) => Container(
              padding: EdgeInsets.symmetric(vertical: px(10)),
              child: Text(
                "${widget.msg[i]}",
                style: TextStyle(
                  color: col("1e1e1e"),
                  fontSize: px(26),
                ),
              ),
            ),
          ),
        ),
      ),
      actions: <Widget>[
        CupertinoDialogAction(
          child: Text(
            "${widget.closeText}",
            style: TextStyle(
              color: col("909399"),
              fontSize: px(34),
            ),
          ),
          onPressed: () {
            if (widget.closeWillClose) {
              Navigator.pop(context);
            }
            if (widget.closeFn != null) {
              widget.closeFn();
            }
          },
        ),
        CupertinoDialogAction(
          child: widget.timeOut > 0
              ? Text(
                  "${widget.timeOut - count}s",
                  style: TextStyle(
                    color: col("5640c6"),
                    fontSize: px(34),
                    fontWeight: FontWeight.bold,
                  ),
                )
              : Text(
                  "${widget.confirmText}",
                  style: TextStyle(
                    color: col("5640c6"),
                    fontSize: px(34),
                    fontWeight: FontWeight.bold,
                  ),
                ),
          onPressed: widget.timeOut == 0
              ? () {
                  if (widget.confirmWillClose) {
                    Navigator.pop(context);
                  }
                  if (widget.confirmFn != null) {
                    widget.confirmFn();
                  }
                }
              : null,
        ),
      ],
    );
  }
}

class _Intimacy extends StatefulWidget {
  final String token;

  _Intimacy({@required this.token, Key key}) : super(key: key);

  @override
  __IntimacyState createState() => __IntimacyState();
}

class __IntimacyState extends State<_Intimacy> {
  final circular = Path()
    ..moveTo(55, 15)
    ..cubicTo(55, 12, 50, 0, 30, 0)
    ..cubicTo(0, 0, 0, 37.5, 0, 37.5)
    ..cubicTo(0, 55, 20, 77, 55, 95)
    ..cubicTo(90, 77, 110, 55, 110, 37.5)
    ..cubicTo(110, 37.5, 110, 0, 80, 0)
    ..cubicTo(65, 0, 55, 12, 55, 15)
    ..close();

  UserGetAnchorWechatModel info;

  bool isUpIntimacy = false;

  int upGold = 0;

  // 分钟计时
  int timeCount = 0;

  @override
  void initState() {
    super.initState();
    final bloc = BlocProvider.of<LiveBloc>(context);
    bloc.minuteStream.listen((event) {
      timeCount++;
      upGold = info?.timePrice ?? 0;
      isUpIntimacy = true;
      setState(() {});
      io();
      Timer(
        Duration(seconds: 3),
        () {
          isUpIntimacy = false;
          setState(() {});
        },
      );
    });

    // socket监听消息
    final not = Global.socketNot;
    if (not.value != null) {
      not.value
          .map((str) => jsonDecode(str))
          .where((cls) => cls['datatype'] == 'allgift')
          .map((cls) => WsAllGiftModel.fromJson(cls['data']))
          .where((cls) {
        UserState user = state(context, 'user');
        final isAnchor = user.info?.memberType == 1;
        String ut = isAnchor ? widget.token : user.info.memberToken;
        String at = !isAnchor ? widget.token : user.info.memberToken;
        return cls.anchorToken == at && ut == cls.token;
      }).listen(
        (res) {
          UserApis.giftInfo(res.id).then((req) {
            if (req == null) return;
            upGold = res.number * req['gift_gold'];
            isUpIntimacy = true;
            setState(() {});
            io();
            Timer(
              Duration(seconds: 3),
              () {
                isUpIntimacy = false;
                setState(() {});
              },
            );
          });
        },
      );
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    io();
  }

  io() {
    UserState user = state(context, 'user');
    final isAnchor = user.info?.memberType == 1;
    String ut = isAnchor ? widget.token : user.info.memberToken;
    String at = !isAnchor ? widget.token : user.info.memberToken;
    UserApis.userGetAnchorWechat(ut, at).then((res) {
      if (res == null) return;
      info = UserGetAnchorWechatModel.fromJson(res);
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    double value = 0;
    final intimacy = (info?.spend ?? 0) + timeCount * (info?.timePrice ?? 0);
    final need = info?.require ?? 0;
    if (info != null) {
      // 主播未开放微信
      if (info.open == 0 || info.wxaccount == null) {
        return SizedBox.shrink();
      }

      if (intimacy > need) {
        value = 1;
      } else {
        value = intimacy / need;
      }
    }

    return Positioned(
      left: px(30),
      top: px(300),
      child: Stack(
        overflow: Overflow.visible,
        children: [
          Transform.scale(
            scale: .3,
            alignment: Alignment.topLeft,
            child: Column(
              children: [
                LiquidCustomProgressIndicator(
                  value: value,
                  valueColor: AlwaysStoppedAnimation(
                    value == 1 ? Colors.red : Colors.pink,
                  ),
                  backgroundColor: Colors.pink[50],
                  direction: Axis.vertical,
                  shapePath: circular,
                ),
                SizedBox(height: px(30)),
                Text(
                  value == 1 ? '亲密度已满' : '$intimacy/$need',
                  style: TextStyle(
                    fontSize: px(100),
                    color: Colors.white,
                    shadows: [
                      Shadow(
                        color: Colors.black,
                        blurRadius: 1,
                        offset: Offset(1, 1),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          if (isUpIntimacy)
            Positioned(
              top: -px(50),
              left: px(30),
              child: Text(
                '+$upGold',
                style: TextStyle(
                  fontSize: px(32),
                  color: Colors.white,
                  shadows: [
                    Shadow(
                      color: Colors.black,
                      blurRadius: 1,
                      offset: Offset(1, 1),
                    ),
                  ],
                ),
              ),
            ),
        ],
      ),
    );
  }
}
